package cn.wolfcode.luowowo.listener;

import cn.wolfcode.luowowo.cache.Util.RedisKeys;
import cn.wolfcode.luowowo.cache.service.IStrategyStatisVORedisService;
import cn.wolfcode.luowowo.cache.service.ITravelStatisVORedisService;
import cn.wolfcode.luowowo.cache.vo.StrategyStatisVO;
import cn.wolfcode.luowowo.cache.vo.TravelStatisVO;
import cn.wolfcode.luowowo.domain.Strategy;
import cn.wolfcode.luowowo.domain.Travel;
import cn.wolfcode.luowowo.service.IStrategyService;
import cn.wolfcode.luowowo.service.ITravelsService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.data.annotation.Reference;
import org.springframework.stereotype.Component;

import java.util.List;

//@Component
public class RedisDataInitListener implements ApplicationListener<ContextRefreshedEvent> {

    @Autowired
    private IStrategyService strategyService;
    @Autowired
    private ITravelsService travelsService;

    @Autowired
    private IStrategyStatisVORedisService strategyStatisVORedisService;

    @Autowired
    private ITravelStatisVORedisService travelStatisVORedisService;
    //Spring容器准备好之后马上执行的方法
    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        System.out.println("---------------攻略begin---------------------");
        //获取所有攻略
        List<Strategy> strategies = strategyService.list();
        //遍历所有攻略
        for (Strategy s : strategies) {
            //判断每个攻略的vo是否已经存在
            if(strategyStatisVORedisService.isVoExists(s.getId())){
                //如果已经存在,则跳过这次循环
                continue;
            }
            //如果不存在,则新建一个
            StrategyStatisVO vo = new StrategyStatisVO();
            //再将攻略对象中的数据拷贝到vo中
            BeanUtils.copyProperties(s,vo);
            //再将vo的攻略id设置为当前攻略的id
            vo.setStrategyId(s.getId());
            //最后将 vo set进redis中去即可
            strategyStatisVORedisService.setStrategyStatisVo(vo);
        }
        System.out.println("---------------攻略end---------------------");

        System.out.println("---------------游记begin---------------------");
        //获取所有游记
        List<Travel> travels = travelsService.list();
        //遍历所有游记
        for (Travel s : travels) {
            //判断每个游记的vo是否已经存在
            if(travelStatisVORedisService.isVoExists(s.getId())){
                //如果已经存在,则跳过这次循环
                continue;
            }
            //如果不存在,则新建一个
            TravelStatisVO vo = new TravelStatisVO();
            //再将游记对象中的数据拷贝到vo中
            BeanUtils.copyProperties(s,vo);
            //再将vo的游记id设置为当前攻略的id
            vo.setTravelId(s.getId());
            //最后将 vo set进redis中去即可
            travelStatisVORedisService.setTravelStatisVo(vo);
        }
        System.out.println("---------------end---------------------");
    }
}